<template>
	<div class="strategy">
		<!--上边-->
		<div class="head">
			<div class="sou">
				<el-form :inline="true" :model="filters"  ref="filters"  class="demo-form-inline">
					<el-form-item label="策略名称" prop="name">
						<el-input v-model="filters.name" ></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmit('filters')">搜索</el-button>
					</el-form-item>
				</el-form>
			</div>
				<div class="zeng"> 
					<el-button type="primary" @click="dialogFormVisible = true">策略新增</el-button>
				</div>
		</div>
		<!--策略信息新增-->
		<el-dialog title="策略新增"  :visible.sync="dialogFormVisible">
			<el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">		  
				<el-form-item label="策略名称" :label-width="formLabelWidth"  prop="name">
						 <el-input v-model="form.name" auto-complete="off" id='nameOnly' style="width:100%"></el-input>
				</el-form-item>
				<el-form-item
				v-for="(domain, index) in form.rule"
				:label="'策略规则' + index"
				:key="domain.key">
						<el-select v-model="domain.effect"  :key="domain.key" placeholder="在线否" style="width:20%">
							<el-option label="是" value="是"></el-option>
							<el-option label="否" value="否"></el-option>
						</el-select>
						<el-select v-model="domain.actions" placeholder="启用否" style="width:20%">
							<el-option label="已启用" value="已启用"></el-option>
							<el-option label="未启用" value="未启用"></el-option>
						</el-select>
						<el-input v-model="domain.resources" style="width:23%"></el-input>
						<el-button @click.prevent="removeDomain(domain)">删除</el-button>
						<el-button @click="addDomain">增加规则</el-button>
					</el-form-item>
				</el-form-item>
				 <el-form-item label="策略描述" :label-width="formLabelWidth" prop="details">
					<el-input v-model="form.details" id="textarea" type="textarea" auto-complete="off" style="width:100%"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('form')" :loading="addLoading">确 定</el-button>
			</div>
		</el-dialog>
		<!--策略信息修改-->
		<el-dialog title="策略修改"  :visible.sync="dialogFormVisible1" >
		 <el-form :model="form1" :rules="rules" ref="form1" label-width="100px" class="demo-ruleForm">
				<el-form-item label="策略名称" :label-width="formLabelWidth" prop="name" >
					 <el-input v-model="form1.name" :disabled=true auto-complete="off" style="width:100%"></el-input>
				</el-form-item>
				<el-form-item
				v-for="(domain, index) in form1.rule"
				:label="'策略规则' + index"
				:key="domain.key">
						<el-select v-model="domain.effect"  :key="domain.key" placeholder="在线否" style="width:20%">
							<el-option label="是" value="是"></el-option>
							<el-option label="否" value="否"></el-option>
						</el-select>
						<el-select v-model="domain.actions" placeholder="启用否" style="width:20%">
							<el-option label="已启用" value="已启用"></el-option>
							<el-option label="未启用" value="未启用"></el-option>
						</el-select>
						<el-input v-model="domain.resources" style="width:23%"></el-input>
						<el-button @click.prevent="removeDomain1(domain)">删除</el-button>
						<el-button @click="modifDomain">增加规则</el-button>
					</el-form-item>
				 <el-form-item label="策略描述" :label-width="formLabelWidth" prop="details" >
					<el-input v-model="form1.details" id="textarea" type="textarea" auto-complete="off" style="width:100%"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible1=false">取消</el-button>
				<el-button type="primary" @click="modifysubmit('form1')" :loading="editLoading">确 定</el-button>
			</div>
		</el-dialog>
		<!--策略规则-->
		<el-dialog title="策略规则"  :visible.sync="policyrules" >
		 <el-form :model="form1" :rules="rules" :disabled="true" ref="form1" label-width="100px" class="demo-ruleForm">
				<el-form-item
				v-for="(domain, index) in form1.rule"
				:label="'策略规则' + index"
				:key="domain.key">
						<el-input v-model="domain.effect" style="width:30%"></el-input>
						<el-input v-model="domain.actions" style="width:30%"></el-input>
						<el-input v-model="domain.resources" style="width:35%"></el-input>
					</el-form-item>
			</el-form>
		</el-dialog>
		<!-- <el-dialog title="策略规则"  :visible.sync="policyrules" >
		 <el-form :model="PolicyRules"  ref="PolicyRules" label-width="100px" class="demo-ruleForm">
				 <el-form-item label="策略规则" id="PolicyRules" :label-width="formLabelWidth">
					<json></json>
				</el-form-item>
			</el-form>
		</el-dialog> -->
			<!--中间内容-->
			<el-table
				:data="tableData"
				border
				v-loading="listLoading"
				:header-cell-class-name="tableheaderClassName"
				:row-class-name="tableRowClassName">
				 	<el-table-column 
						prop="name"
						label="策略名称">
					</el-table-column>
					<el-table-column
						prop="details"
						label="描述"
						width="300%">
					</el-table-column>
					<el-table-column
						prop="rule"
						label="策略规则"
						width="100">
						<template slot-scope="scope">
							<el-button  @click="ruleClick(scope.row)"    size="small" type="text" >
								<span >点击查看规则</span>
							</el-button>
						</template>
					</el-table-column>
					<el-table-column
						prop="createDate"
						label="添加时间">
					</el-table-column>
					 <el-table-column
						prop="lastUpdateDate"
						label="最后一次修改时间">
					</el-table-column>	
				 <el-table-column
					fixed="right"
					label="操作"
					width="100">
					<template slot-scope="scope">
							<el-button   @click="handleClick(scope.row)" size="small" type="text" ><span style=
								"color:#212121">编辑</span>
							</el-button>
							<el-button   @click="Delete(scope.$index,scope.row)"  size="small" type="text">删除
							</el-button>
					</template>
				</el-table-column>
		 </el-table>
		 <!--删除设备密码框-->
		<el-dialog title="删除设备" :visible.sync="deviceWord">
		<el-form :model="devicePassWord" :rules="rules" ref="devicePassWord" label-width="100px" class="demo-ruleForm">
				<el-form-item label="输入登录密码" :label-width="formLabelWidth" prop="passWord">
					<el-input v-model="devicePassWord.passWord" auto-complete="off" style="width:90%"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="deviceWord = false">取 消</el-button>
				<el-button type="primary" @click="deleteDevice('devicePassWord')">确 定</el-button>
			</div>
		</el-dialog>
		<!--底部内容-->
		<div class="di">
			<div style="float:right;width:30%">
				<el-pagination 
				background
				:page-size='pageSize'
				layout="prev, pager, next" 
				@current-change="handleCurrentChange" 
				 :total="total" >
				</el-pagination>
			</div>
		</div>	
</div>
</template>
<script>
import json from '../../components/Json.vue';
import $ from 'jquery';
import util from '../../common/js/date.js';
import { editUser, deletePass,  getUserListPage, removeUser,   addUser, getUserName } from '../../api/api.js';
export default {
	name:'list',
	components:{ json },
	data() {
		return {
			filters: {
				name:''
			},
			tableData: [],
			PolicyRules:{},
			devicePassWord:{
				passWord:null,
			},
			code:true,
			page: 1,
			total: 0,
			pageSize:10,
			pageIndex:1,
			account:null,
			listLoading:false,
			addLoading:false,
			editLoading:false,
			policyrules:false,
			deviceWord:false,
			dialogFormVisible: false,
			dialogFormVisible1: false,
			tenantId:'mingzhu',
			api:"策略分析",
			rules:{
				name:[
					{required:true,message:'名称不能为空！',trigger:'blur'},
					{min:3,max:50,message:'名称长度不正确',trigger:'blur'}
				],
				version:[
					{required:true,message:'版本不能为空',trigger:'blur'},
				],
				address:[{required:true,message:'地址不能为空',trigger:'blur'}],
				details:[
					{required:true,message:'设备描述不能为空',trigger:'blur'},
					{min:3,max:50,message:'设备描述长度不正确',trigger:'blur'}
				],	
				attributes:[{required:true,message:'规则不能为空',trigger:'change'}],				
			},
			form: {
				name:null,
				details:null,
				tenantId:null,
				attributes:'aa',
				rule:[{
					resources:null,
					effect:null,
					actions:null
				}],
			},
			form1: {	
				rule:[
					{
						resources:'1111',
						effect:'是',
						actions:'已启用'
					},
					{
						resources:'2223',
						effect:'否',
						actions:'未启用'
					},
					{
						resources:'3333',
						effect:'是',
						actions:'已启用'
					},
				],
				attributes:'aa',				
				id:null,
				name:null,
				delPara:null,
				details:null,
				createDate:null,
				lastUpdateDate:null,
				tenantId:null,
				delFlag:null,
				rule:{},
			},
			formLabelWidth: '100px',
		};
	},
	watch:{
		dialogFormVisible:function(){
			var that=this;
			this.$nextTick(function(){
				$("#textarea").height(150);
				$('#nameOnly').blur(function() {
					that.getNameOnly($('#nameOnly').val());
				});
			});
		},		
	},
	methods:{
		removeDomain1(item) {
			console.log(item);
			var index = this.form1.rule.indexOf(item)
			console.log(index);
			if (index !== 0) {
				this.form1.rule.splice(index, 1)
			}
		},
		addDomain() {
			this.form.rule.push({
				effect:'是',
				actions:'未启用',
				resources:'33333',
				id:new Date()
			});
		},
		removeDomain(item) {
			console.log(item);
			var index = this.form.rule.indexOf(item)
			console.log(index);
			if (index !== 0) {
				this.form.rule.splice(index, 1)
			}
		},
		modifDomain() {
			this.form1.rule.push({
				effect:'是',
				actions:'未启用',
				resources:'333'
			});
		},
		//验证name的唯一性
		getNameOnly(val){
			let para = {
				thingName: val,
				tenantId:this.tenantId,
				api:this.api,
			};
			console.log(para);
			getUserName(para).then((res) => {
				console.log(res);
				if(res.resultHint==200){
					this.code=true;
				}else{
					this.$message({
						message: '设备名已存在',
						type: 'success'
					});
					this.code=false;
				}
			});
		},
		//获取用户列表
		getUsers() {			
			let para = {
				pageIndex: this.pageIndex,
				content: this.filters.name,
				pageSize:this.pageSize,
				tenantId:this.tenantId,
				api:this.api,
			};
			getUserListPage(para).then((res) => {
				console.log(res);
				this.total = res.data.count;
				this.tableData = res.data.data;
				console.log(this.tableData);
				if(!res.data.count==0){
				for(var i=0;i<res.data.data.length;i++){
					this.tableData[i].createDate = util(this.tableData[i].createDate)
					this.tableData[i].lastUpdateDate = util(this.tableData[i].lastUpdateDate)
				}
				}
			});
		},
		// 分页获取
		handleCurrentChange(val) {
			this.pageIndex=val;
			this.getUsers();
		},
		// 策略搜索
		onSubmit(formName){
			this.$refs[formName].validate((valid) => {
				if (valid) {
					var str=this.filters.name;
					console.log(str);
					var re =/[`~!@#$%^&*_+<>{}'[\]]/im;
					if (re.test(str)){
						this.$message({
							message: '不能有特殊字符',
							type: 'warning'
						});
					}else{
						this.getUsers();
					}			
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		//信息新增确认按钮处理
		submitForm(formName){
			this.$refs[formName].validate((valid) => {
				if (valid) {
						if(this.code){
							// para.rule=JSON.parse($('#add').find('textarea').val());
							let para = Object.assign({}, this.form);
							para.tenantId=this.tenantId,
							para.api=this.api,					
							console.log(para);
							addUser(para).then((res) => {
								console.log(res);
								if(res.resultHint=='策略已存在'){
									this.$message({
										message: '策略名已存在',
										type: 'warning'
									});
									this.$refs['form'].resetFields();							
								}else{
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									this.$refs['form'].resetFields();
									this.dialogFormVisible = false;
									this.getUsers();
								}						
							});
						}else{
							this.$message({
								message: '策略名已存在',
								type: 'success'
							});
							// this.code=false;
						}
				} else {
					console.log('error submit!!');
					this.$refs['form'].resetFields();
					return false;
				}
			});
		},
		ruleClick:function (row) {
			this.policyrules=true;
			console.log(row);
			this.form1.rule=row.rule;
			// this.$nextTick(function(){
			// 	$('#PolicyRules').find('textarea').val(function() {
			// 		return row.rule;
			// 	});
			// });
		},
		//信息修改重置操作
		resetForm:function () {
			this.form1.rule='';
			this.form1.details='';
		},
		//信息修改提交操作
		modifysubmit:function(formName){
			this.$refs[formName].validate((valid) => {
				if (valid) {
					console.log(this.form1);
					let para = Object.assign({}, this.form1);
					para.api=this.api,
					para.tenantId=this.tenantId,
					para.createDate='';
					para.lastUpdateDate='';
					console.log(para);
					editUser(para).then((data) => {
						console.log(data);
						if(data.resultHint==200){
							this.$message({
								message: '提交成功',
								type: 'success'
							});
							this.$refs['form1'].resetFields();
							this.dialogFormVisible1 = false;
							this.getUsers();
						}else{
							this.$message({
								message: '修改失败',
								type: 'success'
							});
						}
					});
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		// 单元格的编辑
		handleClick(row) {
			this.dialogFormVisible1=true;
			// this.$nextTick(function(){
			// 	$('#modify').find('textarea').val(function() {
			// 		return row.rule;
			// 	});
			// 	$("#textarea").height(150);
			// });
			this.form1.id=row.id;
			this.form1.name=row.name;
			this.form1.details=row.details;
			this.form1.rule=row.rule;
			this.form1.createDate=row.createDate;
			this.form1.lastUpdateDate=row.lastUpdateDate;
			this.form1.tenantId=row.tenantId;
			this.form1.delFlag=row.delFlag;
		},
		// 删除数据
		Delete:function(index, row){
			this.$confirm('确认要删除吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				this.delPara = { id: row.id,api:this.api,};
				console.log(this.delPara);
				this.deviceWord=true;
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		// 密码删除
		deleteDevice:function(formName){	
			this.$refs[formName].validate((valid) => {
				if (valid) {
					let para = Object.assign({}, this.devicePassWord);
					para.loginName=this.account,
					deletePass(para).then((data) => {
						if(data.resultHint==200){
							console.log('ididididid',this.delPara);
							removeUser(this.delPara).then((data) => {
								console.log(data);
								if(data.resultHint==200){
									this.listLoading = false;
									this.$message({
										message: '删除成功',
										type: 'success'
									});
									this.getUsers();
									this.deviceWord=false;
									this.devicePassWord.passWord='';
								}else{
									this.$message({
										message: '删除失败',
										type: 'success'
									});
								}
							});
						}else{
							this.$message({
								message: '密码错误',
								type: 'warning'
							});
						}
					});
				} else {
					console.log('error submit!!');
					return false;
				}
			});	
		},
		// 表格样式
		tableRowClassName({rowIndex}) {
			if (rowIndex % 2==0) {
				return 'success-row';
			} else if (rowIndex % 2 !==0) {
				return 'warning-row';
			}
			return '';
		},
		tableheaderClassName() {
			return "table-head-th";
		},
	},
	mounted() {
		this.getUsers();
		var self=this;
		let user = sessionStorage.getItem('user');
		if (user) {
			user = JSON.parse(user);
			console.log(user);
			self.account=user.account;
		}	
	}
};
</script>
<style scoped>
	.strategy{width:90%;margin: 0 auto; }
	.strategy .sou{
		float:left;
	}
	.strategy .head{
		margin-top: 40px;
		margin-bottom: 40px;
		overflow: hidden;
	}
	.strategy .zeng{
		float:right;
	}
	.strategy .di{width:80%;margin-left:0px;position:relative;left:6%;
	 bottom:-50%;line-height:36px;
	 margin-top: 30px;}
</style>
